﻿using System;

namespace JanusLibAing.AutoSave
{
    /// <summary>
    /// Enum data item
    /// Stored enum value
    /// Underlined type must be default (int)
    /// </summary>
    public abstract class DataItemEnumValue : IDataItem
    {
        private Enum enumValue;

        /// <summary>
        /// Initializes a new instance of the <see cref="DataItemString"/> class.
        /// </summary>
        /// <param name="value">The value.</param>
        protected DataItemEnumValue(Enum value)
        {
            enumValue = value;
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            Type underlyingType = Enum.GetUnderlyingType(enumValue.GetType());
            object intValue = Convert.ChangeType(enumValue, underlyingType);
            return intValue.ToString();
        }

        /// <summary>
        /// Parses the specified import value.
        /// </summary>
        /// <param name="importValue">The import value.</param>
        public void ParseValue(string importValue)
        {
            int intValue=-1;
            bool found = false;
            if (int.TryParse(importValue, out intValue))
            {
                Type enumType = enumValue.GetType();
                Array array = Enum.GetValues(enumType);
                foreach (int item in array)
                {
                    if (item == intValue)
                    {
                        found = true;
                        break;
                    }
                }

                if (found)
                {
                    enumValue = (Enum) Enum.ToObject(enumType, intValue);
                }
            }
        }

        /// <summary>
        /// Gets the item name.
        /// </summary>
        /// <value>The name.</value>
        public abstract string Name { get; }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>The value.</value>
        public object Value
        {
            get { return enumValue; }
            set { enumValue = (Enum)value; }
        }

        /// <summary>
        /// Gets or sets the item value.
        /// </summary>
        /// <value>The item value.</value>
        public Enum ItemValue
        {
            get { return enumValue; }
            set { enumValue = value; }
        }
    }
}